package cn.sytton.taffe.framework.datasource;

import cn.sytton.taffe.framework.base.mapper.LogSqlMapper;
import cn.sytton.taffe.framework.datasource.properties.DruidProperties;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 日志库数据源配置类
 *
 * @author skyrock
 */
@Configuration
@MapperScan(basePackages = {"cn.sytton.**.mapper"},
        markerInterface = LogSqlMapper.class,
        sqlSessionFactoryRef = "logSqlSessionFactory")
public class DataSourceLog {

    @Bean(name = "logDataSource")
    @ConfigurationProperties(prefix = "db.log")
    public DataSource getDataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        dataSource.setName(DataSourceType.LOG.name());
        druidProperties.setProperties(dataSource);
        return dataSource;
    }

    @Bean(name = "logDatabaseIdProvider")
    public DatabaseIdProvider getDatabaseIdProvider() {
        return DataSourcePropertiesBuilder.newDatabaseIdProvider();
    }

    @Bean(name = "logSqlSessionFactory")
    public SqlSessionFactory logSqlSessionFactory(@Qualifier("logDataSource") DataSource dataSource,
                                                  @Qualifier("logDatabaseIdProvider") DatabaseIdProvider databaseIdProvider,
                                                  @Qualifier("logMybatisConfiguration") MybatisConfiguration mybatisConfiguration) throws Exception {
        return DataSourcePropertiesBuilder.newSqlSessionFactory(dataSource, databaseIdProvider, "classpath*:/mapper/*.xml", mybatisConfiguration);
    }

    @Bean(name = "logTransactionManager")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("logDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


    @Bean("logSqlSessionTemplate")
    public SqlSessionTemplate logSqlSessionTemplate(@Qualifier("logSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }

    @Bean("logMybatisConfiguration")
    @ConfigurationProperties(prefix = "mybatis-plus.configuration")
    public MybatisConfiguration logMybatisConfiguration() {
        return new MybatisConfiguration();
    }
}


